package com.maple.common.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.text.TextRecognition
import com.google.mlkit.vision.text.chinese.ChineseTextRecognizerOptions
import com.maple.base.base.BaseActivity
import com.maple.common.R
import com.maple.model.data.BundleData
import com.maple.utils.const.ConstKey
import com.maple.utils.ext.toVisible
import com.maple.utils.util.PermissionUtils
import com.maple.utils.util.RequestPermissionResult
import com.maple.utils.util.UIUtils.Companion.parcelable
import java.util.concurrent.Executors

class OcrActivity : BaseActivity() {

    private var bundleData: BundleData? = null

    private var cameraProvider: ProcessCameraProvider? = null

    private var previewView: PreviewView? = null
    private var etResult: EditText? = null
    private var btnConfirm: Button? = null
    override fun getLayoutId(): Int = R.layout.activity_ocr

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        setTitle("识别")
        findViewById<ImageButton>(com.maple.res.R.id.ibtn_title_left)?.let {
            it.toVisible()
            it.setOnClickListener {
                this.onFinish()
            }
        }
        previewView = findViewById(R.id.preview_view)
        etResult = findViewById(R.id.et_result)
        btnConfirm = findViewById(R.id.btn_confirm)
        btnConfirm?.setOnClickListener {
            onForResult()
        }
    }
    override fun initData(savedInstanceState: Bundle?) {

        bundleData = intent?.extras?.parcelable(ConstKey.BundleKey.EXTRA_OBJ)

        PermissionUtils.requestCamera(this, object : RequestPermissionResult{
            override fun onRequestPermissionSuccess() {
                setupCamera()
            }
        })
    }


    private fun setupCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener({
            val cameraProvider = cameraProviderFuture.get()
            bindPreview(cameraProvider)
        }, ContextCompat.getMainExecutor(this))
    }


    /**
     * 绑定 preview
     */
    private fun bindPreview(cameraProvider: ProcessCameraProvider) {
        this.cameraProvider = cameraProvider
        val preview = Preview.Builder().build()
        val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
        preview.setSurfaceProvider(previewView?.surfaceProvider

        )
        val analysis = ImageAnalysis.Builder()
            .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888)
            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
            .build()
        analysis.setAnalyzer(Executors.newSingleThreadExecutor(), this::analyzeImage)
        cameraProvider.bindToLifecycle(this, cameraSelector, preview, analysis)
    }

    /**
     * 解析文本
     */
    @SuppressLint("UnsafeOptInUsageError")
    private fun analyzeImage(imageProxy: ImageProxy) {
        val image = imageProxy.image ?: return
        val inputImage = InputImage.fromMediaImage(image, imageProxy.imageInfo.rotationDegrees)
        val recognizer = TextRecognition.getClient(ChineseTextRecognizerOptions.Builder().build())
        recognizer.process(inputImage)
            .addOnSuccessListener { result ->
                result?.let { r ->
                    val text = r.text
                    if(!TextUtils.isEmpty(text)) {
                        bundleData?.result = text
                        etResult?.let { et ->
                            et.setText(text)
                            et.setSelection(text.length)
                        }
                    }
                }

            }
            .addOnCompleteListener {
                // 释放ImageProxy对象
                imageProxy.close()
            }
            .addOnFailureListener {
                // 处理识别过程中的错误
                it.printStackTrace()
                imageProxy.close()
            }
    }


    private fun onForResult() {
        setResult(RESULT_OK, Intent().putExtra(ConstKey.BundleKey.EXTRA_OBJ,bundleData))
        onFinish()
    }

    override fun onDestroy() {
        super.onDestroy()
        cameraProvider?.unbindAll()
        cameraProvider = null
    }
}